package com.zxw.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zxw.common.config.PropertyMSConfig;
import com.zxw.common.constant.CacheConstants;
import com.zxw.common.constant.Constants;
import com.zxw.common.core.domain.AjaxResult;
import com.zxw.common.core.redis.RedisCache;
import com.zxw.common.utils.sign.Base64;
import com.zxw.common.utils.uuid.IdUtils;
import com.zxw.system.service.ISysConfigService;

/**
 * 验证码操作处理
 * 
 * @author zxw
 */
@RestController
public class CaptchaController
{


    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;
    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
//        创建一个成功的返回对象
        AjaxResult ajax = AjaxResult.success();
//        查询系统是否开启了验证码功能
        boolean captchaEnabled = configService.selectCaptchaEnabled();
//        把是否开启了验证码放到返回对象里面去
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
//            如果没有开启验证码，则直接返回
            return ajax;
        }

        // 创建一个唯一的uuid
        String uuid = IdUtils.simpleUUID();
//        组装验证码的key key =
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;


        // 生成验证码类型
        String captchaType = PropertyMSConfig.getCaptchaType();
//        声明相关变量
        AbstractCaptcha captcha = null; // hutool 生成的验证码对象
        if ("line".equals(captchaType))
        {
            captcha=CaptchaUtil.createLineCaptcha(200,100,PropertyMSConfig.getCaptchaLength(),50);
        }
        else if ("circle".equals(captchaType))
        {
            captcha=CaptchaUtil.createCircleCaptcha(200,100,PropertyMSConfig.getCaptchaLength(),50);
        }
        else if ("shear".equals(captchaType))
        {
            captcha=CaptchaUtil.createShearCaptcha(200,100,PropertyMSConfig.getCaptchaLength(),50);
        }else{
//            交给全局异常处理区去返回
            throw new RuntimeException("验证码类型不存在");
        }

//        取出正确的验证码
        String code =captcha.getCode();
//        把正常验证码放到redis并设置过期时间
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);


        ajax.put("uuid", uuid);
        ajax.put("img", captcha.getImageBase64Data());
        return ajax;
    }
}
